import { hasSubset } from '../advisor/utils';
import type { ChartKnowledge, CustomChart, GetChartConfigProps, Specification } from '../types';
import { findNominalField, findOrdinalField } from './util';

const getChartSpec = (data: GetChartConfigProps['data'], dataProps: GetChartConfigProps['dataProps']) => {
  try {
    const field4Y = dataProps?.filter(field => hasSubset(field.levelOfMeasurements, ['Interval']));
    const nominalField = findNominalField(dataProps);
    const ordinalField = findOrdinalField(dataProps);
    const field4X = nominalField ?? ordinalField;
    if (!field4X || !field4Y || field4Y.length === 0) return null;

    // 计算每个指标的总和
    const sums = field4Y.map(field => ({
      field,
      sum: data.reduce((acc, row) => acc + (Number(row[field.name]) || 0), 0)
    }));
    // 找到总和最小的指标
    const minSumField = sums.reduce((min, cur) => (cur.sum < min.sum ? cur : min), sums[0]).field;
    const spec: Specification = {
      type: 'view',
      data,
      children: [],
    };

    field4Y.forEach(field => {  
      const isBar = field.name === minSumField.name;
      spec.children.push({
        type: isBar ? 'interval' : 'line',
        encode: {
          x: field4X.name,
          y: field.name,
          color: () => field.name,
          series: () => field.name,
        },
        scale: { y: { key:isBar ? 'interval' : 'line'+field.name, } }, 
        axis: {
          y: {
            position: isBar ? 'left' : 'right',
            title:field.name
          }
        }
      });
    });

    return spec;
  } catch (err) {
    console.log(err);
    return null;
  }
};

const ckb: ChartKnowledge = {
  id: 'multi_column_line_mix_chart',
  name: 'multi_column_line_mix_chart',
  alias: ['multi_column_line_mix_chart'],
  family: ['MixedCharts'],
  def: 'multi_column_line_mix_chart uses bars and lines to show multiple measures in a nominal dimension',
  purpose: ['Comparison', 'Trend'],
  coord: ['Cartesian2D'],
  category: ['Statistic'],
  shape: ['Bars', 'Lines'],
  dataPres: [
    { minQty: 2, maxQty: '*', fieldConditions: ['Interval'] },
    { minQty: 1, maxQty: 1, fieldConditions: ['Nominal'] },
  ],
  channel: ['Color', 'Direction', 'Position'],
  recRate: 'Recommended',
  toSpec: getChartSpec,
};

/* 订制一个图表需要的所有参数 */
export const multi_column_line_mix_chart: CustomChart = {
  chartType: 'multi_column_line_mix_chart',
  chartKnowledge: ckb as ChartKnowledge,
  chineseName: '多轴图',
};

export default multi_column_line_mix_chart;